﻿using FriendAD.Core;
using FriendAD.Core.General;
using FriendAD.Core.Types;
using FriendAD.web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FriendAD.web.Areas.Manage.Controllers
{
    [AdminAuthorize]
    public class UserController : Controller
    {
        private UserManager userManager = new UserManager();
        // GET: Manage/User
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 首页数据列表
        /// </summary>
        /// <returns></returns>
        public JsonResult ListJson()
        {
            List<User> list = userManager.FindList().ToList();
            //分页查询需要后期修改前台查询参数
            return Json(list);
        }
        [HttpPost]
        public JsonResult DeleteJson(List<int> ids)
        {
            int _total = ids.Count();
            Response _res = new Response();
            _res = userManager.Delete(ids);
            if (_res.Code == 1 && _res.Data < _total)
            {
                _res.Code = 2;
                _res.Message = "共提交删除" + _total + "名用户,实际删除" + _res.Data + "名用户。\n原因：未知";
            }
            else if (_res.Code == 2)
            {
                _res.Message = "共提交删除" + _total + "名管理员,实际删除" + _res.Data + "名管理员。";
            }
            return Json(_res);
        }

        /// <summary>
        /// 添加用户分部视图
        /// </summary>
        /// <returns></returns>
        public PartialViewResult AddPartialView()
        {
            return PartialView();
        }
        [ValidateAntiForgeryToken]
        [HttpPost]
        public JsonResult AddJson(User user)
        {
            Core.Types.Response _res = new Core.Types.Response();
            if (ModelState.IsValid)
            {
                if (userManager.HasAccount(user.UserName))
                {
                    _res.Code = 0;
                    _res.Message = "用户已存在";
                }else
                {
                    user.RegistrationTime = DateTime.Now;
                    user.Status = 3;
                    user.Password = Security.SHA256(user.Password);

                    _res = userManager.Add(user);
                }
            }
            else
            {
                _res.Code = 0;
                _res.Message = General.GetModelErrorString(ModelState);
            }
            return Json(_res);
        }
    }
}